package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/coder/websocket"
	"github.com/coder/websocket/wsjson"
)

// func test() {

// 	upgrader := websocket.Upgrader{
// 		ReadBufferSize:  1024,
// 		WriteBufferSize: 1024,
// 	}
// 	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
// 		conn, err := upgrader.Upgrade(w, r, nil)
// 		if err != nil {
// 			log.Println(err)
// 			return
// 		}
// 		defer conn.Close()

// 		//做一次读写
// 		var v interface{}
// 		err = conn.ReadJSON(&v)
// 		if err != nil {
// 			log.Println(err)
// 			return
// 		}

// 		log.Println("接收到客户端：%s\n", v)

// 		err = conn.WriteJSON(v)
// 		if err != nil {
// 			log.Println(err)
// 			return
// 		}
// 	})
// 	log.Fatal(http.ListenAndServe(":8081", nil))
// }

func test() {
	//HTTP
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "HELLO HTP")
	})

	//websocket
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		conn, err := websocket.Accept(w, r, nil)
		if err != nil {
			log.Println(err)
			return
		}
		defer conn.Close(websocket.StatusInternalError, "内部出错")

		//创建一个10秒后过期的上下文
		ctx, cancel := context.WithTimeout(r.Context(), time.Second*10)
		defer cancel()

		var v interface{}
		err = wsjson.Read(ctx, conn, &v)
		if err != nil {
			log.Println(ctx)
			return
		}
		log.Printf("客户端收到请求: %v", v)

		err = wsjson.Write(ctx, conn, "hello sebsocket client")
		if err != nil {
			log.Println(ctx)
			return
		}

		conn.Close(websocket.StatusNormalClosure, "")
	})
	log.Fatal(http.ListenAndServe(":8081", nil))
}
